yjx.controller('chatController',['$rootScope','$scope','$timeout','$fetch','imService','modalService','webimHandler','sendCommonMsg','messageHandler','$compile','wxShareService','$location','ipCookie','$init',function($rootScope,$scope,$timeout,$fetch,imService,modalService,webimHandler,sendCommonMsg,messageHandler,$compile,wxShareService,$location,ipCookie,$init){
        $scope.headMsg="与基因云客服对话中";
    $rootScope.isNew = true; //收到新消息的flg  获取历史消息时为false
    $scope.productList = ipCookie('productList');
    $init.title("客服");
    //$rootScope.user = {
    //    userId:3,
    //    nickname:'syuenkei',
    //    avatar:'http://wx.qlogo.cn/mmopen/vi_32/ibytib2JRtibvnkl1iaaKLL3l5TtczMNicMtAVic0k2WRVDTmUzNldSVeVGGCbOoG4E1XnzA6Mich3FL5L5PcLsRAibibJA/0',
    //}

        if($rootScope.loginInfo && $rootScope.loginInfo.identifier ){
                $timeout(function(){
                    initProduct();
                });
        }else{
                $fetch.fetch(
                    '/im/getUserSig',
                    {
                     params:{
                             userId:$rootScope.userId
                     },
                        cache:false
                    }
                ).then(function(data){
                            if(data) {
                                $rootScope.loginInfo =data;
                                //imService.webimLogin(data);
                                webim.login(
                                    data, listeners, options,
                                    function (resp) {
                                        imService.setProfilePortrait();
                                        /*新建连接 */
                                        initDemoApp();
                                    },
                                    function (err) {
                                        modalService.mainMsgError("与客户建立连接失败,请稍后重试")
                                        //alert(err.ErrorInfo);
                                    }
                                );
                            }

                    }).catch(function(e){
                            modalService.mainMsgError(e.msg);
                    })
        }

    var options = {
        'isAccessFormalEnv': true, //是否访问正式环境，默认访问正式，选填
        'isLogOn': false //是否开启控制台打印日志,默认开启，选填
    }
    //监听事件
    var listeners = {
        "onConnNotify": onConnNotify //监听连接状态回调变化事件,必填
        ,
        "onMsgNotify": onMsgNotify //监听新消息(私聊，普通群(非直播聊天室)消息，全员推送消息)事件，必填
        ,
    };
    //监听连接状态回调变化事件
     function onConnNotify(resp) {
        switch (resp.ErrorCode) {
            case webim.CONNECTION_STATUS.ON:
                webim.Log.warn('连接状态正常...');
                break;
            case webim.CONNECTION_STATUS.OFF:
                webim.Log.warn('连接已断开，无法收到新消息，请检查下你的网络是否正常');
                break;
            default:
                webim.Log.error('未知连接状态,status=' + resp.ErrorCode);
                break;
        }
    };

//监听新消息(私聊(包括普通消息、全员推送消息)，普通群(非直播聊天室)消息)事件
//newMsgList 为新消息数组，结构为[Msg]
    function onMsgNotify(newMsgList) {
        var newMsg;
        for (var j in newMsgList) {//遍历新消息
            newMsg = newMsgList[j];
            webimHandler.handlderMsg(newMsg);//处理新消息
        }
    }
    /*初始化*/
    function initDemoApp(){
        /*我需要得到当前客服的id*/
      $fetch.fetch(
          '/im/customer/service'
      ).then(function(data){
              $timeout(function(){
                  //console.log(data);
                  $rootScope.service = {};
                  $rootScope.service.userId = data.accountId;
                  $rootScope.service.nickname= data.nick;
                  $rootScope.service.avatar = data.avatar;
                  webim.syncMsgs(onMsgNotify);
                  $timeout(function(){
                      initMessage($rootScope.service);
                      initProduct();
                  })
              })
          }).catch(function(e){
              modalService.mainMsgError(e.msg);
          })
    }

    /**初始化产品消息 */
   function initProduct(){
       var htmlCollection = document.getElementsByClassName('proItemN5');
        if($scope.productList&& $scope.productList.length>0){
            for(var i=0;i<$scope.productList.length;i++){
                var msg = htmlCollection[i].outerHTML;
                sendCommonMsg.onSendMsg(msg)
            }
            // ipCookie.remove('productList',ipCookiesParam);
        }

   }
    /*发送消息*/
    var mytext = angular.element(document.getElementById("send_msg_text"));
        $scope.sendMsg = function($event){
            $rootScope.isNew = true;
            var msgContent = mytext.html();
            if(!msgContent){
                return
            }else{
                 sendCommonMsg.onSendMsg(msgContent)
                mytext.html('');
            }
            //}
        }
    /*插入表情*/
    $(function(){
        $('.c-face').qqFace({
            id : 'facebox5',
            assign:'send_msg_text',/**/
            path:'common/img/face/'	//表情存放的路径
        });
    });

    /*点击表情改变c-container的scrolltop*/
    $scope.scrollTop = function(){
        var chatContainer =  document.getElementById("chatContainer")
        chatContainer.scrollTop = chatContainer.scrollHeight - chatContainer.clientHeight;
    }

/*初始化消息*/
    function initMessage(user){
        var maxLength = 20;
        $rootScope.messageListShow=[];
        /*从messageList中获取当前窗口的所有消息*/
        $rootScope.messageListShow = messageHandler.getCurMessageAllContent($rootScope.messageList,user.userId);
        var localLength = messageHandler.getCurMessageContentLength(messageHandler.getMyMessage(),user.userId);
        if(typeof ($rootScope.messageListShow) == "undefined" || !$rootScope.messageListShow.length>0){
            //messageList中没有当前窗口的消息则从localstorage中获取
            var rootLength = messageHandler.getCurMessageContentLength($rootScope.messageList,user.userId);
            var endInx = localLength - rootLength;
            var messageList2 = messageHandler.getCurMessageContent(messageHandler.getMyMessage(),user.userId,maxLength,endInx);
            if(typeof (messageList2) != "undefined" ){
                messageHandler.pushContent(user,messageList2);
                if(messageList2.length>=maxLength){
                    $scope.more='';/*查看更多消息*/
                }
            }
            $rootScope.messageListShow = messageHandler.getCurMessageAllContent($rootScope.messageList,user.userId);
            if(typeof ($rootScope.messageListShow) == "undefined"  ||$rootScope.messageListShow.length<=0 ){
                //如果localstorage中没有则初始化当前窗口消息对象
                $rootScope.messageListShow= [];
                $scope.more = '';
            }
        }else{
            if(localLength - $rootScope.messageListShow.length  >0){
                $scope.more='';/*查看更多消息*/
            }else{
                $scope.more = '';
            }
        }
    }

    /*获取更多消息*/
    $scope.getMore = function(){
        var maxLength = 20;
        $rootScope.isNew = false;
        //从localstorage中获取更多
        var localLength = messageHandler.getCurMessageContentLength(messageHandler.getMyMessage(), $rootScope.service.userId);
        var rootLength = messageHandler.getCurMessageContentLength($rootScope.messageList,$rootScope.service.userId);
        var endInx = localLength - rootLength;
        var moreMmessagelist =messageHandler.getCurMessageContent(messageHandler.getMyMessage(),$rootScope.service.userId,maxLength,endInx);
        var moreMmessagelistRev = moreMmessagelist.reverse();
        //console.info(moreMmessagelistRev);
        var messageList2 = messageHandler.getCurMessageAllContent($rootScope.messageList,$rootScope.service.userId);
        if(moreMmessagelist && moreMmessagelist.length>0){
            for(var i = 0 ;i <moreMmessagelistRev.length ;i++){
                messageList2.unshift(moreMmessagelistRev[i]);
            }
            messageHandler.pushContent($rootScope.service,messageList2);
            if( moreMmessagelist.length < maxLength){
                $scope.more='已没有更多消息';
            }
        }else{
            $scope.more='已没有更多消息';
        }
    }


    /*使用微信接口调用手机相册选择图片*/
    $scope.choosePic = function(){
        //$timeout(function(){
            chooseImage();
        //})
    }

    function chooseImage(){
        //alert("chooseImage==============")
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                
                if(res.localIds) {
                    // alert("chooose"+localIds);
                    wx.uploadImage({
                        localId: res.localIds[0], // 需要上传的图片的本地ID，由chooseImage接口获得
                        isShowProgressTips: 0, // 默认为1，显示进度提示
                        success: function (res) {
                            var serverId = res.serverId; // 返回图片的服务器端ID
                            // alert(serverId);
                            upload(res.serverId);
                        }
                    });
                }
            }
        })
    }

    function upload(serverId){
        /*调后端接口上传到自己服务器 返回链接*/
        if(!serverId){
            return
        }
        $fetch.fetch(
            '/wechat/downImage',
            {
                params:{
                    mediaId:serverId
                },
                type:'post'
            }
        ).then(function(data){
                var imgUrl = data;
                // alert(imgUrl)
                //console.log("上传图片成功============="+imgUrl);
                //imgUrl = "http://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIDrNvuKMlMZrtVrWLSj7Xn6RicOPZMa4I4icUH4onn0nJJeG2ANrDsjCpYWibqKg6zO22G6McKHBlMQ/0"
                var html='<img src="'+imgUrl
                html+='" class="imgAppend"/>'
                //var html = '<p>'+imgUrl+'</p>'
                var $html = $compile(html)($scope);
                mytext.append($html)
                var msgContent = mytext.html();
                sendCommonMsg.onSendMsg(msgContent)
                mytext.html('');
            }).catch(function(e){
                modalService.mainMsgError(e.msg);
            })
    }
}]);
/*滚动条控制*/
yjx.directive('scrollDown',['$rootScope','$timeout',function($rootScope,$timeout){
    return{
        restrict:'EA',
        scope:false,
        link: function($scope,$element,attr){
            $scope.$watch(attr.scrollDown ,function(newVals){
                $timeout(function(){
                    //var chatContent = angular.element("#chatContent");
                    //console.info($rootScope.isNew);
                    if($rootScope.isNew){
                        $element[0].scrollTop = $element[0].scrollHeight - $element[0].clientHeight
                        //console.info(chatContent.scrollTop());
                    }else{
                        //获取历史消息时保持滚动条在顶部
                        $element[0].scrollTop = 0;

                    }

                })
            },true)
        }
    }
}]).directive('imgHandler',['modalService',function(modalService){
    return{
        restrict:'A',
        link:function($scope,elem,attr){
            elem.bind('click',function(){
                //console.log(elem);
                //if(elem.closest)
                /*图片点击全屏查看 不包括表情图*/
                if(angular.element(elem.context.childNodes[0]).hasClass('imgAppend')){
                    // if(elem.hasClass('imgLarge')){
                    //     elem.removeClass('imgLarge')
                    // }else{
                    //     elem.addClass('imgLarge')
                    // }
                    var url = angular.element(elem.context.childNodes[0]).attr('src')
                    modalService.openImgLarge(url)
                }else{
                    return
                }
            })
        }
    }
}])